
# -*- coding: utf-8 -*-

import debug
import urllib2
import base64
import threading
import logging

from CamBase import CamBase

class IPUX(CamBase):
	'''
	LSカメラ用カメラコントロールクラス
	'''
	@debug.entry
	def __init__(self, config):
		self.model = config['model']
		self.uri = config['address']
		self.username = config['username']
		self.passwd = config['passwd']
		self.MovieCaptureThread = None
		self.MovieEventObj = None
		self.AudioCaptureThread = None
		self.AudioEventObj = None

	def __getResObj(self, uri):
		passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
		passmgr.add_password(None, uri, self.username, self.passwd)
		authInfo = urllib2.HTTPBasicAuthHandler(passmgr)
		opener = urllib2.build_opener(authInfo)
		urllib2.install_opener(opener)
		reqObj = urllib2.Request(uri)
		
		try:
			resObj = urllib2.urlopen(reqObj)
		except urllib2.HTTPError, e:
			logging.debug('urllib2.HTTPError:' + e.message)
			return {'Success':False, 'Response':None, 'Message':e.message}
		except urllib2.URLError, e:
			logging.debug('urllib2.URLError:' + e.message )
			return {'Success':False, 'Response':None, 'Message':e.message}
		
		return {'Success':True, 'Response':resObj, 'Message':'OK'}

	def __getConfig(self, section, item):
		confObj = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=list&group='+section+'&name='+item)
		if confObj['Success'] is False:
			logging.debug(confObj['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':confObj['Response'].read().split('=')[1], 'Message':'OK'}

	def get_content_length(self, data):
		if data[0:15] != 'Content-Length:':
			return None
		return int(data[16:])

	def MovieCaptureLoop(self, target, storage):
		i = 0
		camCaptures = self.__getResObj('http://'+self.uri+'/cgi/mjpg/mjpeg.cgi')
		
		if camCaptures['Success'] is False:
			logging.debug(confObj['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
			
		while not(self.MovieEventObj.is_set()):
			try:
				frameData = camCaptures['Response'].readline()
				content = None

				content_length = self.get_content_length(frameData)
				if content_length is None:
					continue
				else:
					content = camCaptures['Response'].read(content_length)
					# skip crlf
					content = content[2:]
					# skip payload header
					content = content[28:]
				
					if content:
						storage.save_frame(target, content, '.jpg')
			except:
				camCaptures = self.__getResObj('http://'+self.uri+'/cgi/mjpg/mjpeg.cgi')

	def AudioCaptureLoop(self, target, storage):
		i = 0
		camCaptures = self.__getResObj('http://'+self.uri+'/cgi/audio/audio.cgi?type=PCM')
		
		if camCaptures['Success'] is False:
			logging.debug(confObj['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
			
		while not(self.AudioEventObj.is_set()):
			try:
				frameData = camCaptures['Response'].readline()
				content = None

				content_length = self.get_content_length(frameData)
				if content_length is None:
					continue
				else:
					content = camCaptures['Response'].read(content_length)
					# skip crlf
					content = content[2:]
					# skip payload header
					content = content[28:]
					
					if content:
						storage.save_frame(target, content, '.pcm')
			except:
				camCaptures = self.__getResObj('http://'+self.uri+'/cgi/audio/audio.cgi?type=PCM')
	

	@debug.entry
	def getCamStatus(self):
		'''
		IPカメラの接続状態を取得する
		return:
			Success:True/False
			Response: OK/None
			Message: OK/Bad Response
		'''
		res = self.__getResObj('http://'+self.uri+'/cgi/admin/serverreport.cgi')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getIPAdder(self):
		'''
		IPカメラのIPアドレスを取得
		return: 
			Success: True/False
			Responce: IPアドレス(IPv4形式, 文字列)/None
			Message: OK/Bad Response
		'''
		res = self.__getConfig('Network', 'IPAddress')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':res['Response'], 'Message':'OK'}

	@debug.entry
	def getMACAdder(self):
		'''
		IPカメラのMACアドレスを取得
		return: 
			Success: True/False
			Responce: MACアドレス(文字列)/None
			Message: OK/Bad Response
		'''
		res = self.__getConfig('System.Info', 'MACAddress')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':res['Response'], 'Message':'OK'}

	@debug.entry
	def getHTTPport(self):
		'''
		IPカメラのHTTPポートを取得
		return: 
			Success: True/False
			Responce: HTTPポート番号(整数値, デフォルトは80)/None
			Message: OK/Bad Response
		'''
		res = self.__getConfig('System', 'HTTPPort')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':int(res['Response']), 'Message':'OK'}

	@debug.entry
	def setHTTPport(self, ports):
		'''
		IPカメラのHTTPポート番号を設定
		ports: ポート番号(1～65536の整数値)
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		if 1 <= ports <= 65536:
			res = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=System&HTTPPort='+str(ports))
			if res['Success'] is False:
				logging.debug(res['Message'])
				return {'succcess':False, 'Response':None, 'Message':'Bad Response'}
			else:
				return {'Success':True, 'Response':'OK', 'Message':'OK'}
		else:
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}

	@debug.entry
	def getHTTPSport(self):
		'''
		IPカメラのHTTPSポートを取得
		return: 
			Success: True/False
			Responce: HTTPSポート番号(整数値, デフォルトは443)/None
			Message: OK/Bad Response
		'''
		res = self.__getConfig('Network.Advanced.HTTPS', 'HttpsPort')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':False, 'Response':int(res['Response']), 'Message':'OK'}

	@debug.entry
	def setHTTPSport(self, ports):
		'''
		IPカメラのHTTPSポート番号を設定
		ports: ポート番号(1～65536の整数値)
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		if 1 <= ports <= 65536:
			res = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=Network.Advanced.HTTPS&HttpsPort='+str(ports))
			if res['Success'] is False:
				logging.debug(res['Message'])
				return {'Success':False, 'Response':None, 'Message':'Bad Response'}
			else:
				return {'Success':True, 'Response':'OK', 'Message':'OK'}
		else:
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}

	@debug.entry
	def getFormatList(self):
		'''
		ビデオフォーマットリストを取得
		return: 
			Success: True
			Responce: ビデオフォーマットリスト(3個の文字列)
	        Message: OK
		'''
		vlist = ('H.264', 'MPEG4', 'MJPEG')
		return {'Success':True, 'Response':vlist, 'Message':'OK'}

	@debug.entry
	def getVideoFormat(self):
		'''
		現在のビデオフォーマットを取得
		return: 
			Success: True/False
			Responce: 現在のビデオフォーマット(文字列)/None
			Message: OK/Bad Response
		'''
		h264 = self.__getConfig('Hardware', 'H.264')
		if h264['Success'] is False:
			logging.debug(h264['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		
		mpeg4 = self.__getConfig('Hardware', 'MPEG4')
		if mpeg4['Success'] is False:
			logging.debug(mpeg4['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		
		mjpeg = self.__getConfig('Hardware', 'MJPEG')
		if mjpeg['Success'] is False:
			logging.debug(mjpeg['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		
		if int(h264['Response']) is 1:
			vformat = "H.264"
		elif int(mpeg4['Response']) is 1:
			vformat = "MPEG4"
		elif int(mjpeg['Response']) is 1:
			vformat = "MJPEG"

		return {'Success':True, 'Response':vformat, 'Message':'OK'}

	@debug.entry
	def setVideoFormat(self, vformat):
		'''
		IPカメラのビデオフォーマットを変更する
		vformat: 変更したいビデオフォーマット(文字列)
			ex.) H.264, MPEG4, MJPEG
		return: 
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		vlist = self.getFormatList()
		if not (vformat in vlist['Response']):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		
		for vformat in vlist['Response']:
			if vformat is vformat:
				res = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=Hardware&'+vformat+'=1')
			else:
				res = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=Hardware&'+vformat+'=0')
			
			if res['Success'] is False:
				logging.debug(res['Message'])
				return {'Success':False, 'Response':None, 'Message':'Bad Response'}

		return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getBrightnessList(self):
		'''
		設定可能な明るさリストを取得する
		return: 
			Success: True
			Responce: 明るさリスト(5個のリスト)
			Message: OK
		'''
		blist = {'Lowest':1, 'Low':25, 'Normal':50, 'High':75, 'Highest':100}
		return {'Success':True, 'Response':blist, 'Message':'OK'}

	@debug.entry
	def getBrightness(self):
		'''
		IPカメラから現在の明るさを取得する
		return:
			Success: True/False
			Responce: 現在の明るさ(文字列)/None
			Message: OK/Bad Response
		'''
		res1 = self.__getConfig('ImageSource.IO.Sensor', 'Brightness')
		if res1['Success'] is False:
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		brightness = int(res1['Response'])
		res2 = self.getBrightnessList()
		blist = res2['Response']
		
		if blist['Lowest'] <= brightness < blist['Low']:
			blevel =  'Lowest'
		elif blist['Low'] <= brightness < blist['Normal']:
			blevel = 'Low'
		elif blist['Normal'] <= brightness < blist['High']:
			blevel = 'Normal'
		elif blist['High'] <= brightness < blist['Highest']:
			blevel =  'High'
		else:
			blevel = 'Highest'

		return {'Success':True, 'Response':blevel, 'Message':'OK'}
	
	@debug.entry
	def setBrightness(self, brightness):
		'''
		IPカメラの明るさを変更する
		brightness: 変更したい明るさ(文字列)
			ex.) Highest, High, Normal, Low, Lowest
		return:
			Succcess: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		res1 = self.getBrightnessList()
		blist = res1['Response']
		
		if not (brightness in blist):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		bnum = blist[brightness]
		
		res2 = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=ImageSource.IO.Sensor&Brightness='+str(bnum))
		if res2['Success'] is False:
			logging.debug(res2['Message'])
			return {'Success':False, 'Response':None, 'Message':' Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}
		
	@debug.entry
	def getSaturationList(self):
		'''
		IPカメラで設定できる彩度のリストを取得する
		return: 
			Success: True
			Responce: 彩度リスト(5個のリスト)
			Message: OK
		'''
		slist = {'Lowest':1, 'Low':25, 'Normal':50, 'High':75, 'Highest':100}
		return {'Success':True, 'Response':slist, 'Message':'OK'}

	@debug.entry
	def getSaturation(self):
		'''
		IPカメラの現在の彩度を取得する
		return:
			Success: True/false
			Responce: 現在の彩度(文字列)/None
			Message: OK/Bad Response
		'''
		res1 = self.__getConfig('ImageSource.IO.Sensor', 'ColorLevel')
		if res1['Success'] is False:
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		saturation = int(res1['Response'])

		res2 = self.getSaturationList()
		slist = res2['Response']
		
		if slist['Lowest'] <= saturation < slist['Low']:
			slevel = 'Lowest'
		elif slist['Low'] <= saturation < slist['Normal']:
			slevel = 'Low'
		elif slist['Normal'] <= saturation < slist['High']:
			slevel = 'Normal'
		elif slist['High'] <= saturation < slist['Highest']:
			slevel = 'High'
		else:
			slevel = 'Highest'

		return {'Success':True, 'Response':slevel, 'Message':'OK'}

	@debug.entry
	def setSaturation(self, saturation):
		'''
		IPカメラの彩度を変更する
		saturation: 変更したい彩度(文字列)
			ex.) Highest, High, Normal, Low, Lowest
		return: 
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		res1 = self.getSaturationList()
		slist = res1['Response']
		
		if not(saturation in slist):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		snum = slist[saturation]
		
		res2 = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=ImageSource.IO.Sensor&ColorLevel='+str(snum))
		if res2['Success'] is False:
			logging.debug(res2['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getContrastList(self):
		'''
		IPカメラで設定できるコントラストのリストを取得する
		 return: 
		 	Success: True
		 	Responce: コントラストリスト(5個のリスト)
		 	Message: OK
		'''
		clist = {'Lowest':1, 'Low':25, 'Normal':50, 'High':75, 'Highest':100}
		return {'Success':True, 'Response':clist, 'Message':'OK'}

	@debug.entry
	def getContrast(self):
		'''
		IPカメラから現在のコントラストを取得する
		return:
			Success: True/False
			Responce: 現在のコントラスト(文字列)/None
			Message: OK/Bad Response
		'''
		res1 = self.__getConfig('ImageSource.IO.Sensor', 'Contrast')
		if res1['Success'] is False:
			logging.debug(res1['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		contrast = res1['Response']

		res2 = self.getContrastList()
		clist = res2['Response']

		if clist['Lowest'] <= contrast < clist['Low']:
			clevel = 'Lowest'
		elif clist['Low'] <= contrast < clist['Normal']:
			clevel = 'Low'
		elif clist['Normal'] <= contrast < clist['High']:
			clevel = 'Normal'
		elif clist['High'] <= contrast < clist['Highest']:
			clevel = 'High'
		else:
			clevel = 'Highest'

		return {'Success':True, 'Response':clevel, 'Message':'OK'}

	@debug.entry
	def setContrast(self, contrast):
		'''
		IPカメラのコントラストを変更する
		contrast: 変更したいコントラスト(文字列)
			ex.) Highest, High, Normal, Low, Lowest
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		res1 = self.getContrastList()
		clist = res1['Response']
		
		if not(contrast in clist):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		
		cnum = clist[contrast]
		res = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=ImageSource.IO.Sensor&Contrast='+str(cnum))
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getResolutionList(self):
		'''
		IPカメラに設定できる解像度のリストを取得する
		return: 
			Success: True
			Responce: 解像度リスト(3個のリスト)
			Message: OK
		'''
		rlist = ("640*480", "320*240", "160*120")
		return {'Success':True, 'Response':rlist, 'Message':'OK'}

	@debug.entry
	def getResolution(self):
		'''
		IPカメラの現在の解像度を取得する
		return:
			Success: True/False
			Responce: 現在の解像度(文字列)/None
			Message: OK/Bad Response
		'''
		res = self.__getConfig('Image.MJPEG', 'Resolution')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		
		index = int(res['Response'])
		res2 = self.getResolutionList()
		rlist = res2['Response']
		return {'Success':True, 'Response':rlist[index], 'Message':'OK'}
	
	@debug.entry
	def setResolution(self, resolution):
		'''
		IPカメラの解像度を変更する
		resolution: 変更したい解像度(文字列)
			ex.) 640*480, 320*240, 160*120
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		res1 = self.getResolutionList()
		rlist = res1['Response']
		
		if not(resolution in rlist):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		
		res2 = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=Image.MJPEG&Resolution='+str(rlist.index(resolution)))
		if res2['Success'] is False:
			logging.debug(res2['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'} 

	@debug.entry
	def getQualityList(self):
		'''
		IPカメラに設定できる動画品質のリストを取得する
		return:
			Success: True
			Responce: 動画品質リスト(5個のリスト)
			Message: OK
		'''
		qlist = ('Lowest', 'Low', 'Normal', 'High', 'Highest')
		return {'Success':True, 'Response':qlist, 'Message':'OK'}
	
	@debug.entry
	def getQuality(self):
		'''
		現在の動画品質を取得する
		return:
			Success: True/False
			Responce: 現在の動画品質(文字列)/None
			Message: OK/Bad Response
		'''
		res  = self.__getConfig('Image.MJPEG', 'Quality')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'getQuality Error(getConfig Error)'}
		
		quality = int(res['Response'])
		res2 = self.getQualityList()
		qlist = res2['Response']
		return {'Success':True, 'Response':qlist[quality], 'Message':'OK'}

	@debug.entry
	def setQuality(self, quality):
		'''
		動画品質の変更を行う
		quality: 変更したい動画品質
			ex.) Highest, High, Normal, Low, Lowest
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		res = self.getQualityList()
		qlist = res['Response']

		if not(quality in qlist):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		
		res2 = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=Image.MJPEG&Quality='+str(qlist[quality]))
		if res2['Success'] is False:
			logging.debug(res2['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getFpsList(self):
		'''
		IPカメラに設定できるフレームレートのリストを取得する
		return: 
			Success: True
			Responce: フレームレートリスト(6個のリスト)
			Message:OK
		'''
		flist = (5, 10, 15, 20, 25, 30)
		return {'Success':True, 'Response':flist, 'Message':'OK'}
		
	@debug.entry
	def getFps(self):
		'''
		現在のフレームレートを取得する
		return: 
			Success: True/False
			Responce: フレームレート(整数値)/None
			Message: OK/Bad Response
		'''
		res = self.__getConfig('Image.MJPEG', 'Framerate')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':int(res['Response']), 'Message':'OK'}

	@debug.entry
	def setFps(self, fps):
		'''
		フレームレートの変更を行う
		fps: 変更したいフレームレート(整数値)
			ex.) 5, 10, 15 ...
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/Bad Response/Bad Parameter
		'''
		res1 = self.getFpsList()
		flist = res1['Response']

		if not(fps in flist):
			return {'Success':False, 'Response':None, 'Message':'Bad Parameter'}
		
		res2 = self.__getResObj('http://'+self.uri+'/cgi/admin/param.cgi?action=update&group=Image.MJPEG&Framerate='+str(fps))
		if res2['Success'] is False:
			logging.debug(res2['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getLogs(self):
		'''
		IPカメラ自身のログを取得する
		return:
			Success: True/False
			Responce: ログの実体/None
			Message: OK/Bad Response
		'''
		res = self.__getResObj('http://'+self.uri+'/cgi/admin/systemlog.cgi')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':camLogs.read(), 'Message':'OK'}
	
	@debug.entry
	def getSnapshot(self):
		'''
		IPカメラから静止画を取得する
		return:
			Success: True/False
			Responce: 画像データ(バイナリ, JPEG)/None
			Message: OK/Bad Response
		'''
		res = self.__getResObj('http://'+self.uri+'/cgi/jpg/image.cgi')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':res['Message']}
		else:
			return {'Success':True, 'Response':res['Response'].read(), 'Message':'OK'}

	@debug.entry
	def startMovieCapture(self, target, storage):
		'''
		IPカメラで動画キャプチャを開始する
		target: 撮影対象となるカメラのコンフィグ名
			ex.) cam1, cam2, cam3 ...
		storage: 保存するストレージクラス
		return: 
			Success: True/False
			Responce: OK/None
			Message: OK/NG
		'''
		if self.MovieCaptureThread is not None:
			logging.debug('movie capture thread is started already.')
			return {'Success':False, 'Response':None, 'Message':'movie capture thread is started already.'}

		self.MovieEventObj      = threading.Event()
		self.MovieEventObj.clear()

		self.MovieCaptureThread = threading.Thread(target=self.MovieCaptureLoop, args=(target, storage))
		self.MovieCaptureThread.start()

		return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def endMovieCapture(self):
		'''
		IPカメラの動画キャプチャを終了させる
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/None
		'''
		if self.MovieCaptureThread is None:
			return {'Success':False, 'Response':None, 'Message':'movie capture thread is not running.'}
		
		# Wait to Finish Thread
		while self.MovieCaptureThread.is_alive():
			self.MovieEventObj.set()
			self.MovieCaptureThread.join(0.1)

		logging.debug('movie capture thread is finished.')
		self.MovieCaptureThread = None
		self.MovieEventObj      = None
            
		return {'Success':True, 'Response':'OK','Message':'OK'}

	@debug.entry
	def startAudioCapture(self, target, storage):
		'''
		IPカメラで音声キャプチャを開始する
		target: 撮影対象となるカメラのコンフィグ名
			ex.) cam1, cam2, cam3 ...
		storage: 保存するストレージクラス
		return: 
			Success: True/False
			Responce: OK/None
			Message: OK/NG
		'''
		if self.AudioCaptureThread is not None:
			logging.debug('audio capture thread is started already.')
			return {'Success':False, 'Response':None, 'Message':'audio capture thread is started already.'}

		self.AudioEventObj      = threading.Event()
		self.AudioEventObj.clear()

		self.AudioCaptureThread = threading.Thread(target=self.AudioCaptureLoop, args=(target, storage))
		self.AudioCaptureThread.start()

		return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def endAudioCapture(self):
		'''
		IPカメラの音声キャプチャを終了させる
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/None
		'''
		if self.AudioCaptureThread is None:
			return {'Success':False, 'Response':None, 'Message':'audio capture thread is not running.'}
		
		# Wait to Finish Thread
		while self.AudioCaptureThread.is_alive():
			self.AudioEventObj.set()
			self.AudioCaptureThread.join(0.1)

		logging.debug('audio capture thread is finished.')
		self.AudioCaptureThread = None
		self.AudioEventObj      = None
            
		return {'Success':True, 'Response':'OK','Message':'OK'}
